package com.springboot.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.springboot.admin.entity.CateDto;
import com.springboot.admin.entity.CommentsDto;
import com.springboot.admin.entity.NavigationDto;
import com.springboot.admin.entity.PagesDto;
import com.springboot.admin.mail.MailSenderBoot;
import com.springboot.admin.mapper.AccountDao;
import com.springboot.admin.mapper.AdminDao;
import com.springboot.admin.mapper.NavigationDao;
import com.springboot.admin.mapper.PagesDao;
import com.springboot.admin.security.service.GetCurrentLoginUsername;
import com.springboot.admin.service.AccountService;
import com.springboot.admin.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class AdminServiceImpl implements AdminService {
  @Autowired
  MailSenderBoot mailSenderBoot;
  @Autowired
  AccountService accountService;
  @Autowired
  NavigationDao navigationDao;
  @Autowired
  AccountDao accountDao;
  @Autowired
  AdminDao  adminDao;
  @Autowired
  GetCurrentLoginUsername getCurrentLoginUsername;
  @Autowired
  PagesDao pagesDao;
  @Autowired
  RedisTemplate redisTemplate;

  public Map getDetail(String id){
    PagesDto pagesDto  = adminDao.getDetail(Integer.parseInt(id));
    // 浏览量加1
    adminDao.updateViews(pagesDto);
    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("result", pagesDto);
    return resultMap;
  };

  public Map getListByCatePage(PagesDto pagesDto){

    int cate = pagesDto.getCate();
    int page = pagesDto.getPage();
    int pageSize = pagesDto.getPageSize();

    Map<String, Object> resultMap = new HashMap<>();
    List<PagesDto> list = new ArrayList<>();

    // 使用pageHelper分页
    PageInfo<PagesDto> pagesDtoPageInfo;
    PageHelper.startPage(page,pageSize);

    // 获取当前登录人
    String username = getCurrentLoginUsername.getUsername();

    if (cate > 0){
      list = adminDao.getListByCateByUserId(cate,page,username);
      pagesDtoPageInfo = new PageInfo<>(list);
    } else {
      if (username.equals("admin")){
        // 如果是管理员则查询所有数据,否则查当前登录人
        list =  adminDao.getAll(page);
        pagesDtoPageInfo = new PageInfo<>(list);
      } else {
        list =  adminDao.getAllByUsername(page,username);
        pagesDtoPageInfo = new PageInfo<>(list);
      }
    }

    resultMap.put("total", pagesDtoPageInfo.getTotal());
    resultMap.put("result", pagesDtoPageInfo.getList());
    return resultMap;
  };

  public void insertComment(CommentsDto commentsDto){
    pagesDao.insertComment(commentsDto);
    pagesDao.updateCommentNum(commentsDto);
    // 有新评论发送邮件通知
    Map siteInfo = accountDao.getSiteInfo();
    mailSenderBoot.sendMail((String)siteInfo.get("siteEmail"), "有新的评论：" + commentsDto.toString(), "评论通知");

  }

  public Map getUserListByPage(String page){
    Map<String, Object> resultMap = new HashMap<>();
    List<Map> list = new ArrayList<>();
    list = accountService.getUserList(Integer.parseInt(page));
    resultMap.put("result", list);
    return resultMap;
  };

  public Map getRoleList(){
    Map<String, Object> resultMap = new HashMap<>();
    List<Map> list = new ArrayList<>();
    list = accountService.getRoleList();
    resultMap.put("result", list);
    return resultMap;
  };

  public void updateRole(Map roleMap){
    List<Map> list = (List<Map>) roleMap.get("roleList");
    String username = (String)roleMap.get("username");
    accountService.deleteRolesByUsername(username);
    for (Map map: list){
      accountService.insertRole(username,(String) map.get("roleId"));
    }
  };

  public void insertRole(Map map){
    String username = (String) map.get("username");
    String password = (String)map.get("password");
    String email = (String)map.get("email");
    accountService.insertUser(username,password, email);
  };

  public Map<String, Object> getNavList(Map map){
    Map<String, Object> resultMap = new HashMap<>();
    PageHelper.startPage((int)map.get("page"),(int)map.get("pageSize"));
    List<NavigationDto> list = navigationDao.getAll();
    PageInfo<NavigationDto> pagesDtoPageInfo = new PageInfo<>(list);
    resultMap.put("result", pagesDtoPageInfo.getList());
    resultMap.put("total", pagesDtoPageInfo.getTotal());
    return resultMap;
  };

  public void insertOne(PagesDto pagesDto) {
    pagesDto.setUid(UUID.randomUUID().toString());
    adminDao.insertOne(pagesDto);

    String kw = pagesDto.getKeywords();
    if (kw.indexOf(',') > 0){
      String[] singleKey = kw.split(",");
      for(String sk: singleKey){
        adminDao.insertKeyWords(sk);
      }
    } else {
      adminDao.insertKeyWords(kw);
    }
  }

  public void delOne(int id) {
    String username = getCurrentLoginUsername.getUsername();
    // int 转String
    // 更新文章前删除缓存
    redisTemplate.delete(String.valueOf(id));
    //  管理员可以删除任何文章
    if (username.equals("admin")){
      adminDao.delOneByadmin(id);
    } else {
      adminDao.delOne(id, username);
    }
  }

  public void updateOne(PagesDto pagesDto) throws Exception {
    String createBy = adminDao.getCreateByid(pagesDto.getId());
    String username = getCurrentLoginUsername.getUsername();
    // 更新文章前删除缓存
    redisTemplate.delete(String.valueOf(pagesDto.getId()));
    // 更新操作需判断当前内容是由本人创建
    if (!createBy.equals(username)){
      throw new Exception("无权更新");
    }
    adminDao.updateOne(pagesDto);
  }

  public void insertCate(CateDto cateDto) {
    adminDao.insertCate(cateDto);
  }

  public void updateCate(CateDto cateDto) {
    adminDao.updateCate(cateDto);
  }

  public void delCate(int id) {
    adminDao.delCate(id);
  }

  public void delComment(int id) {
    adminDao.delComment(id);
  }

  public void generateKeywords() {

    adminDao.deleteKeyWords();
    List list =  adminDao.getKeyWords();
    for(Object item:list){
      if (!item.equals("")){
        String kw = (String) item;
        if (kw.indexOf(',') > 0){
          String[] singleKey = kw.split(",");
          for(String sk: singleKey){
            log.info("singleKey:"+sk);
            adminDao.insertKeyWords(sk);
          }
        } else {
          adminDao.insertKeyWords(kw);
        }
      }
    }
  }

  public void clearCache() {
    Set<String> keys = redisTemplate.keys("*");
    Iterator<String> iterator = keys.iterator();
    while (iterator.hasNext()){
      boolean res =  redisTemplate.delete(iterator.next());
      log.info("del-res",res);
    }
  }

  public Object getCateList(){
    Map<String, Object> resultMap = new HashMap<>();
    resultMap.put("result", adminDao.getCate());
    return resultMap;
  };

  public void revertCate(CateDto cateDto) {
    adminDao.revertCate(cateDto);
  }
}